package cn.lijiguo.concurrency.part1.ch06;

/**
 * RightWayStopThreadInProd
 * 在实际开发中正确的方式停止线程2
 * 最佳实战：在 cache 语句中调用 Thread.currentThread().interrupt() 来回复设置中断状态，
 *  以便在后续的执行中，依然能够检查到刚才的中断信号
 *  回到 刚才的 RightWayStopThreadInProd 类中，让它跳出
 * @author lijiguo
 * @date 2020/1/6 11:19
 */
public class RightWayStopThreadInProd2 implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new RightWayStopThreadInProd2(), "t1");
        t1.start();

        Thread.sleep(1000);
        t1.interrupt();
    }

    @Override
    public void run() {
        while (true) {
            if(Thread.currentThread().isInterrupted()) {
                System.out.println("线程即将终止---");
                break;
            }
            System.out.println("go...");

            reInterrupted();
        }
    }

    /**
     * 使用 方法签名 抛出异常
     * @throws InterruptedException
     */
    private void reInterrupted() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }
}
